/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package controller.user;

import javax.inject.Named;
import javax.enterprise.context.SessionScoped;
import java.io.Serializable;
import java.util.*;
import javax.ejb.EJB;
import javax.faces.context.FacesContext;
import model.*;
import javax.faces.application.FacesMessage;
import helper.*;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import javax.el.ELContext;

/**
 *
 * @author shinji
 */
@Named(value = "u_memberManagedBean")
@SessionScoped
public class MemberManagedBean implements Serializable {

    @EJB
    private RoleFacade roleFacade;
    @EJB
    private StateFacade stateFacade;
    @EJB
    private Member1Facade member1Facade;
    private boolean isLogin = false;
    private Member1 member = new Member1();
    private int IDCountry = 0;
    private List<State> lstState = new ArrayList<State>();
    private List<Member1> FriendListCombined = new ArrayList<>();
    private List<Member1> FriendSuggestionList = new ArrayList<>();
    private List<Member1> FriendRequestList = new ArrayList<>();
    private Friend selectFriend = new Friend();

    public Friend getSelectFriend() {
        return selectFriend;
    }

    public void setSelectFriend(Friend selectFriend) {
        this.selectFriend = selectFriend;
    }

    public List<State> getLstState() {
        return lstState;
    }

    public void setLstState(List<State> lstState) {
        this.lstState = lstState;
    }

    public int getIDCountry() {
        return IDCountry;
    }

    public void setIDCountry(int IDCountry) {
        this.IDCountry = IDCountry;
    }

    public Member1 getMember() {
        return member;
    }

    public void setMember(Member1 member) {
        this.member = member;
    }

    public List<Member1> getFriendListCombined() {
        return FriendListCombined;
    }

    public void setFriendListCombined(List<Member1> FriendListCombined) {
        this.FriendListCombined = FriendListCombined;
    }

    public List<Member1> getFriendSuggestionList() {
        return FriendSuggestionList;
    }

    public void setFriendSuggestionList(List<Member1> FriendSuggestionList) {
        this.FriendSuggestionList = FriendSuggestionList;
    }

    public List<Member1> getFriendRequestList() {
        return FriendRequestList;
    }

    public void setFriendRequestList(List<Member1> FriendRequestList) {
        this.FriendRequestList = FriendRequestList;
    }

    /**
     * Creates a new instance of MemberManagedBean
     */
    public MemberManagedBean() {
    }

    /**
     * ********************************************
     */
    public void create() {
        try {
            member.setPassword(helper.PasswordEncryption.MD5(member.getPassword()));
            member.setIDPermission(roleFacade.find(2));
            member.setExpirationDate(getYesterdayDateString());
            
            AlbumManagedBean amb = get_AlbumManagedBean();
            member.setAvatar(amb.upload());
            
            member1Facade.create(member);
            goRedirect("login.xhtml");
        } catch (Exception e) {
            set_message(FacesMessage.SEVERITY_ERROR, "Register Error", "You register error !!!");
        }
    }

    /**
     * ********************************************
     */
    public void verifyLogin(String template) {
        try {
            if (!this.isLogin) {
                switch (template) {
                    case "admin":
                        goRedirect("../login.xhtml");
                        break;

                    case "user":
                        goRedirect("login.xhtml");
                        break;
                }
            }
        } catch (Exception e) {
        }
    }

    public void fixpage(String name_page) {
        try {
            List<Rights> lstRights = new ArrayList<Rights>();
            boolean flag = false;

            for (RoleRights rr : member.getIDPermission().getRoleRightsList()) {
                if (rr.getRights().getName().equals(name_page) && rr.getAgree() == true) {
                    flag = true;
                    break;
                }
            }

            if (!flag) {
                goRedirect("../index.xhtml");
            }

        } catch (Exception e) {
        }
    }

    public void handleStateChange() {
        try {
            lstState = new ArrayList<State>();

            for (State s : stateFacade.getStateByCountryId(IDCountry)) {
                lstState.add(s);
            }
        } catch (Exception e) {
            lstState = null;
        }
    }

    public void login() {
        try {
            member.setPassword(PasswordEncryption.MD5(member.getPassword()));

            if (member1Facade.isUsername(member)) {
                member = (Member1) member1Facade.get_Member_Username(member.getUsername());
                isLogin = true;
                refreshFriendListCombined();
                refreshFriendSuggestionList();
                if (member.getIDPermission().getName().equals("admin")) {
                    goRedirect("faces/administrator/index.xhtml");
                } else {
                    goRedirect("faces/index.xhtml");
                }
            } else {
                set_message(FacesMessage.SEVERITY_WARN, null, "Username or password wrong ");
            }
        } catch (Exception e) {
            set_message(FacesMessage.SEVERITY_WARN, null, "Username or password swrong !!!");
        }
    }

    public void logout(String template) {
        try {
            member = new Member1();
            isLogin = false;
            switch (template) {
                case "admin":
                    goRedirect("../login.xhtml");
                    break;

                case "user":
                    goRedirect("login.xhtml");
                    break;
            }
        } catch (Exception e) {
        }
    }

    public void goRedirect(String page) {
        try {
            FacesContext context = FacesContext.getCurrentInstance();
            context.getExternalContext().redirect(page);
        } catch (Exception ex) {
        }
    }

    public void refreshFriendListCombined() {
        member = this.member1Facade.find(member.getId());
        List<Member1> LM = this.member1Facade.GetFriendListCombined(member.getId());
        /*List<Member1> LM = new ArrayList<>();
        for (Friend f : member.getFriendList()) {
            if (f.getRequest()) {
                LM.add(f.getIDFriend());
            }
        }
        for (Friend f : member.getFriendList1()) {
            if (f.getRequest()) {
                LM.add(f.getIDMember());
            }
        } */      
        FriendListCombined = LM;
    }

    public void refreshFriendSuggestionList() {
        List<Member1> LM = new ArrayList<>();
        for (Member1 m : this.member1Facade.findAll()) {
            if (this.member1Facade.isFriend(member, m) == false && member.getId() != m.getId()) {
                LM.add(m);
            }
        }

        List<Member1> LM2 = new ArrayList<>();
        Random r = new Random();
        for (int i = 0; i < 5; i++) {
            if (LM.size() < 1) {
                break;
            }
            int temp = r.nextInt(LM.size());
            LM2.add(LM.get(temp));
            LM.remove(temp);
        }
        FriendSuggestionList = LM2;
    }
    
    public String Get_User_Avatar(){
        if(member.getAvatar() == null || member.getAvatar()==""){
            return "default_avatar.jpg";
        }
        else return member.getAvatar();
    }
    
    public void RefreshFriendRequestList(){
        List<Member1> LM = new ArrayList<>();
        RefreshMember();
        LM = member1Facade.GetRequestedFriendList(member);
        this.FriendRequestList = LM;
    }

    public void RefreshMember(){
        member = member1Facade.find(member.getId());
    }
    
    public void DetailMemberRedirect(Member1 m){
        MemberDetailManagedBean mdmb = get_MemberDetailManagedBean();
        mdmb.setMember(m);
        goRedirect("memberdetail.xhtml");
    }
    
    // <editor-fold defaultstate="collapsed" desc=" Set message ">
    private void set_message(FacesMessage.Severity severity, String title, String message) {
        try {
            FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(severity, title, message));

        } catch (Exception e) {
            FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, "Error", "Error message !!!"));
        }
    }
    // </editor-fold> 

    // <editor-fold defaultstate="collapsed" desc=" Get yesterday's date ">
    private Date getYesterdayDateString() {
        Calendar cal = Calendar.getInstance();
        cal.add(Calendar.DATE, -1);
        Date d = cal.getTime();
        return d;
    }
    // </editor-fold> 
    
    private MemberDetailManagedBean get_MemberDetailManagedBean() {
        ELContext elContext = FacesContext.getCurrentInstance().getELContext();
        MemberDetailManagedBean mmb = (MemberDetailManagedBean) FacesContext.getCurrentInstance().getApplication()
                .getELResolver().getValue(elContext, null, "u_memberDetailManagedBean");
        return mmb;
    }
    
    private AlbumManagedBean get_AlbumManagedBean() {
        ELContext elContext = FacesContext.getCurrentInstance().getELContext();
        AlbumManagedBean mmb = (AlbumManagedBean) FacesContext.getCurrentInstance().getApplication()
                .getELResolver().getValue(elContext, null, "u_albumManagedBean");
        return mmb;
    }
}
